<template>
  <base-layout
    :visibleContent2="true"
    :visibleContent3="true"
    :visibleContent4="true"
    :visibleContent5="true"
    :dialogVisible="dialogVisible"
    :dialogTitle="dialogTitle"
    @dialog-close="dialogClose"
    v-if="showPage"
  >
    <template #contentPanel>
      <el-form
        :inline="true"
        ref="fromdata"
        :show-message="false"
        :hide-required-asterisk="true"
        :model="fromdata"
        :rules="rules"
        label-width="90px"
        label-position="right"
      >
        <el-row>
          <el-col :span="12">工单信息</el-col>
        </el-row>
        <el-divider content-position="center"></el-divider>
        <el-row>
          <el-col :span="6">
            <el-form-item label="工单编号:" prop="workOrderCode">
              <el-input disabled v-model.number="fromdata.workOrderCode" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单据日期:" prop="receiptsTime">
              <el-date-picker
                disabled
                v-model="fromdata.receiptsTime"
                type="date"
                style="width: 195px"
                placeholder="请选择"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="车牌号:" prop="licensePlateNumber">
              <el-input
                clearable
                v-model="fromdata.licensePlateNumber"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="车型:" prop="licensePlateNumber">
              <CarModel v-model="carModels" ref="carModel" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单备注:" prop="remark">
              <textarea clearable v-model="fromdata.remark" class="w-200"></textarea>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <template #contentPanel2>
      <div v-if="fromdata.workOrderCode">
        <ProjectList
          ref="ProjectList"
          @setTotalAmount="setTotalAmount"
          :list="fromdata.projectList"
        />
      </div>
    </template>

    <template #contentPanel3>
      <div v-if="fromdata.workOrderCode">
        <PartsList
          ref="PartsList"
          @setTotalAmount="setTotalAmount"
          :list="fromdata.partsList"
        />
      </div>
    </template>

    <template #contentPanel4>
      <div v-if="fromdata.workOrderCode">
        <BoutiqueList
          ref="BoutiqueList"
          @setTotalAmount="setTotalAmount"
          :list="fromdata.jpList"
        />
      </div>
    </template>

    <template #contentPanel5>
      <div class="text_right" v-if="fromdata.workOrderCode">
        <p>
          项目总金额+配件总金额+精品总金额：
          <span class="color_red">￥{{ fromdata.amount }}</span>
        </p>
        <p>
          项目优惠金额+配件优惠金额+精品优惠金额：
          <span class="color_red">￥{{ fromdata.discountAmount }}</span>
        </p>
        <p>
          报价金额 <span class="color_red">￥{{ fromdata.shouldAmount }}</span>
        </p>
        <p>
          <el-button type="primary" @click="submitOrder">{{
            fromdata.id ? "保存" : "开单"
          }}</el-button>
        </p>
      </div>
    </template>
  </base-layout>
</template>
<script>
import ProjectList from "@/views/after-sale/workOrderManage/quotation/create/projectList"; //拆分-项目列表
import PartsList from "@/views/after-sale/workOrderManage/sell/create/partsList"; //拆分-配件列表
import BoutiqueList from "@/views/after-sale/workOrderManage/sell/create/boutiqueList"; //拆分-精品列表

import { getUserOrTem } from "@/utils/index";
import { CarBrand } from "@/components/index"; //项目选择组件
import {
  addQuote,
  getQuoteById,
  editQuote,
  quoteGetWorkOrderCode,
} from "@/api/after-sale/workOrderManage/quotation";
import { parseTimeToYMDHMS, getDict, getStoreId } from "@/utils";
import baseMixin from "@/mixins/base";
import moment from "moment";

export default {
  components: { CarBrand, ProjectList, PartsList, BoutiqueList },
  mixins: [baseMixin({})],
  data() {
    return {
      fromdata: {
        amount: undefined,
        carBrandName: "",
        carModelId: undefined,
        carSeriesId: undefined,
        carBrandId: undefined,
        discountAmount: undefined,
        licensePlateNumber: "",
        partsList: [],
        pickCarId: undefined,
        projectList: [],
        jpList: [],
        receiptsTime: "",
        remark: "",
        shouldAmount: undefined,
        storeId: getStoreId(),
        workOrderCode: "",
      },
      rules: {},
      dict: {},
      carModels: [],
      showPage: true, 
    };
  },
  watch: {
    carModels: {
      handler(value) {
        if (value) {
          this.fromdata = {
            ...this.fromdata,
            carBrandId: this.carModels[0],
            carSeriesId: this.carModels[1],
            timeType: this.carModels[2],
            carModelId: this.carModels[3],
          };
        }
      },
      deep: true,
    },
    // fromdata: {
    //   deep: true,
    //   handler (newValue, oldValue) {
    //     try {
    //       let { projectList, jpList, partsList, ...data } = newValue;
    //       const { ProjectList, PartsList, BoutiqueList } = this.$refs;
    //       PartsList.partsList = partsList;
    //       ProjectList.projectList = projectList;
    //       BoutiqueList.jpList = jpList;
    //       console.log(jpList);
    //     } catch (error) {
    //       throwError(error)
    //     }

    //   }
    // }
  },
  async created() {
    this.fromdata.receiptsTime = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    this.dict = getDict(["客户会员等级", "客户类型", "班组类型", "收费类型"]);
    const id = this.$route.query && this.$route.query.id;
    let pickCarId = this.$route.query.pickCarId;
    if (id) {
      const { data } = await getQuoteById(id);
      if (data) {
        this.fromdata = data;
        this.carModels = [
          this.fromdata.carBrandId,
          this.fromdata.carSeriesId,
          this.fromdata.timeType,
          this.fromdata.carModelId,
        ];
      }
    }
    // 接车单跳过来
    else if (pickCarId) {
      this.showPage = false;
      this.fromdata.pickCarId = pickCarId;
      if (!id) {
        let data = this.$route.query.data;
        this.fromdata = { ...data.clientCar, ...data.client };
        if(data.carProjects) {
          this.fromdata.projectList = data.carProjects;
        }
        if (data.carParts) {
          this.fromdata.partsList = data.carParts;
        }
        this.carModels = [
          this.fromdata.carBrandId,
          this.fromdata.carSeriesId,
          this.fromdata.timeType,
          this.fromdata.carModelId,
        ];
      }
      const { data } = await quoteGetWorkOrderCode();
      this.fromdata.workOrderCode = data;
      this.fromdata.receiptsTime = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
      this.showPage = true;
    } else {
      const { data } = await quoteGetWorkOrderCode();
      this.fromdata.workOrderCode = data;
    }
  },
  methods: {
    //设置总金额、优惠劵查询
    setTotalAmount() {
      const { ProjectList, PartsList, BoutiqueList } = this.$refs;
      this.fromdata.amount =
        ProjectList.totalAmount + PartsList.totalAmount + BoutiqueList.totalAmount;
      this.fromdata.shouldAmount =
        ProjectList.totalDiscountAmount +
        PartsList.totalDiscountAmount +
        BoutiqueList.totalDiscountAmount;
      this.fromdata.discountAmount = this.fromdata.amount - this.fromdata.shouldAmount;
    },
    submitOrder() {
      this.$refs.fromdata.validate((valid) => {
        if (valid) {
          const { ProjectList, PartsList, BoutiqueList } = this.$refs;
          this.fromdata = {
            ...this.fromdata,
            receiptsTime: this.fromdata.receiptsTime
              ? parseTimeToYMDHMS(this.fromdata.receiptsTime)
              : "",
            partsList: PartsList.partsList,
            projectList: ProjectList.projectList,
            jpList: BoutiqueList.jpList,
          };
          console.log;
          this.saveData();
        } else {
          return false;
        }
      });
    },
    async saveData() {
      const { success } = this.fromdata.id
        ? await editQuote(this.fromdata)
        : await addQuote(this.fromdata);
      if (success) {
        this.$message({
          message: "操作成功",
          type: "success",
        });
        this.closeRouter();
      } else {
        this.$message.error("操作失败");
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.text_right {
  text-align: right;
}
.color_red {
  font-size: 26px;
  color: red;
}
.ft18 {
  font-size: 18px;
}
</style>
